import { useEffect } from "react";
import _ from "lodash";
import { useForm } from "@mantine/form";
import { get, set, del } from "idb-keyval";

function useTabbyForm(path, key, options) {
  const form = useForm(options);

  //初始化effect
  useEffect(() => {
    get(`[${path}]${key}`).then((val) => {
      if (val) {
        form.setValues(val);
      }
    });
  }, []);

  //data 值变化 effect
  useEffect(() => {
    if (!form.isDirty()) {
      del(`[${path}]${key}`);
      return;
    }

    get(`[${path}]${key}`).then((val) => {
      if (_.isEqual(val, form.values)) {
        return;
      } else {
        set(`[${path}]${key}`, form.values);
      }
    });
  }, [JSON.stringify(form.values)]);

  return form;
}

function conditionalInit(path, key, form, values) {
  const cloned = _.cloneDeep(values);

  form.setInitialValues(cloned);
  get(`[${path}]${key}`).then((val) => {
    if (!val) {
      form.initialize(cloned);
    } else {
      form.setInitialValues(cloned);
    }
  });
}

export { useTabbyForm, conditionalInit };
